import json
import time
from DrissionPage import Chromium,ChromiumOptions
# 启动或接管浏览器，并创建标签页对象
from DrissionPage._elements.none_element import NoneElement

from config import redis_config
from cookie import cookie_to_dict
from redis_api import get_redis
from util.string.index import get_substring_between
co= ChromiumOptions()
# co.set_proxy('http://localhost:8080')
tab = Chromium(addr_or_opts=co).latest_tab
redis = get_redis(redis_config)
#邮箱密码
mail = 'beginvpnchannel@gmail.com'
password = 'dEbUg2024@@@'
# 跳转到登录页面
sign_in_url = 'https://account.booking.com/sign-in'
tab.get(sign_in_url)
#等待跳转结束
tab.wait.doc_loaded()
# 获取当前 URL
current_url = tab.url
if sign_in_url not in current_url:
    tab.ele('#:r0:').click()
    tab.ele('@tag()=button').click()
tab.console.start()
tab.run_js('console.log(JSON.stringify(booking.env));')
data = tab.console.wait()
# 输出：DrissionPage
env = json.loads(data.text)
print(json.dumps(env, indent=4))
# 定位到账号文本框，获取文本框元素
r3_el = tab.ele('#:r3:')
if isinstance(r3_el, NoneElement):
    print("元素不存在 (NoneElement)")
else:
    tab.ele('#:r3:').click()
    time.sleep(1)
tab.wait.ele_displayed('#username')
tab.ele('#username').clear()
tab.ele('#username').input(mail)
#提交邮箱
time.sleep(0.2)
tab.ele('css=button[type="submit"]').click()
# # 定位到密码文本框并输入密码
tab.wait.load_start()
tab.wait.ele_displayed('css=input[type="password"]')
tab.ele('css=input[type="password"]').clear()
tab.ele('css=input[type="password"]').input(password)
#点击登录按钮
tab.ele('css=.nw-signin button[type="submit"]').click()
#等待跳转结束
tab.wait.doc_loaded()
#获取data
tab.wait.ele_displayed('css=script[data-capla-application-context="data-capla-application-context"]')
data_el = tab.ele('css=script[data-capla-application-context="data-capla-application-context"]')
application_data = json.dumps(json.loads(data_el.inner_html), indent=4)
current_html = tab.html
ajaxHeaders = get_substring_between(current_html, 'var ajaxHeaders = ', ';')
ajaxHeaders = ajaxHeaders.replace("'X-Booking-Info': function(){ return (document && document.getElementById('req_info')) ? document.getElementById('req_info').innerHTML : '' },",'')
ajaxHeaders = ajaxHeaders.replace("'X-Booking-Client-Info': function() { return B.et.tracked() },",'')
ajaxHeaders = ajaxHeaders.replace("encodeURIComponent(",'')
ajaxHeaders = ajaxHeaders.replace(")",'')
ajaxHeaders = ajaxHeaders.replace("'",'"')
redis.set(f'env_{mail}',json.dumps(env, indent=4))
redis.set(f'application_data_{mail}',application_data)
# redis.set(f'cookie_str_{mail}',data.text)
# redis.set(f'cookie_dict_{mail}',cookie_dict)
redis.set(f'ajax_headers_{mail}',ajaxHeaders.replace("\n", "").replace(" ", "")
)

#跳转到个人中心
personal_url = 'https://account.booking.com/mysettings/personal?aid='+str(env['aid'])
tab.get(personal_url)

